<template>
  <div class="content-wrap">
    <div class="organization-content">
      <div class="left-panel">
        <Tree key="unitName" :data="organizationOption" :render="renderContent" @on-select-change="selectTreeNode"
          @on-toggle-expand="changeExPand" @on-contextmenu="handleContextMenu">
          <template slot="contextMenu">
            <DropdownItem @click.native="handleMenuEdit" style="color: #1e6fff;">编辑</DropdownItem>
            <DropdownItem @click.native="handleMenuConfig" style="color: #ed4014">配置</DropdownItem>
        </template>
        </Tree>
      </div>
      <div class="right-panel">
        <div class="button-wrap">
          <cus-button class="mb_10" type="primary" size="small" v-permission="20" @onClick="addChildNode" :disabled="!selectedTreeNode.unitName ||
            selectedTreeNode.unitLevelCode == 'KITCHEN'
            ">添加</cus-button>
        </div>
        <div class="table-wrap">
          <cusTable :border="true" :loading="loading" :columns="organCol" :data="orgDataList"
            :size="vuex_config.tableSize" :bottomClass="['cus_page']">

            <template slot-scope="{ row, index }" slot="operation">
              <Button v-if="row.unitLevelCode != 'KITCHEN'" type="primary" size="small" style="margin-right: 5px"
                @click="editOrg(row, index)">编辑</Button>
              <Button type="error" size="small" style="margin-right: 5px" @click="deleteOrg(row, index)"
                v-permission="40">删除</Button>
              <Button v-if="row.unitLevelCode != 'KITCHEN'" type="primary" size="small"
                @click="resetPassword(row, index)">重置密码</Button>
            </template>
          </cusTable>
        </div>
        <cus-page
            :data="pages"
            class="cus_page mt_20"
            @pageChange="handleSubmit()"
          ></cus-page>
      </div>
    </div>
    <editContextModal ref="editContextModal"></editContextModal>
    <reportedConfigModal ref="reportedConfigModal" ></reportedConfigModal>
    <cus-modal ref="addOrgModal" :title="modalTitle" @onOk="modalSubmit" @on-visible-change="statusChange">
      <div>
        <Form ref="addNodeForm" :model="addNodeFormData" :rules="ruleValidate" :label-width="120" class="add-org-form">
          <FormItem label="上级单位">
            <Input clearable maxlength="20" v-model="selectedTreeNode.unitName" disabled></Input>
          </FormItem>
          <FormItem label="区域" prop="kitchenArea">
            <Select v-model="addNodeFormData.kitchenArea" :disabled="modalType == 'edit'">
              <Option v-for="item in areaList" :key="item.kitchenArea" :value="item.kitchenArea">{{ item.kitchenAreaName
              }}
              </Option>
            </Select>
          </FormItem>
          <FormItem v-if="addType == 'addSubUnit'" label="单位属性" prop="unitLevelCode">
            <Select v-model="addNodeFormData.unitLevelCode" :disabled="modalType == 'edit'">
              <Option v-for="item in subNodeTypeList" :key="item.unitLevelCode" :value="item.unitLevelCode">{{
                item.unitLevelCode == "BEN_BU" ? "直属单位" : "下属单位" }}
              </Option>
            </Select>
          </FormItem>
          <FormItem prop="unitName" :rules="{ required: true, message: '名称必填', trigger: 'blur' }"
            :label="addType == 'addSubUnit' ? '单位名称' : '食堂名称'">
            <Input clearable maxlength="20" v-model="addNodeFormData.unitName" placeholder="请输入名称"></Input>
          </FormItem>
          <FormItem label="单位代号" v-if="addType == 'addSubUnit'" prop="codeName">
            <Input clearable maxlength="20" v-model="addNodeFormData.codeName" placeholder="请输入代号"></Input>
          </FormItem>
          <FormItem label="单位番号" v-if="addType == 'addSubUnit'" :required="false" prop="designation">
            <Input clearable maxlength="20" v-model="addNodeFormData.designation" placeholder="请输入番号"></Input>
          </FormItem>
          <FormItem label="食堂人数" v-if="addType != 'addSubUnit'" prop="strength"
            :rules="{ required: true, type: 'number', message: '请输入食堂人数', trigger: 'change' }">
            <InputNumber :min="1" :max="1000000" :precision="0" v-model="addNodeFormData.strength" placeholder="食堂人数"
              style="width: 100%"></InputNumber>
          </FormItem>
          <FormItem v-if="addType != 'addSubUnit'" label="管理员账号" prop="loginName"
            :rules="{ required: true, message: '请输入管理员账号', trigger: 'blur' }">
            <Input clearable maxlength="20" v-model="addNodeFormData.loginName" :disabled="modalType == 'edit'"
              placeholder="默认密码12345"></Input>
          </FormItem>
          <FormItem label="联系人" prop="contactName">
            <Input clearable maxlength="20" placeholder="请输入联系人" v-model="addNodeFormData.contactName"></Input>
          </FormItem>
          <FormItem label="联系电话" prop="contactPhone" v-if="addType == 'addCanteen'">
            <Input placeholder="请输入联系电话" clearable maxlength="20" v-model="addNodeFormData.contactPhone"></Input>
          </FormItem>
          <FormItem label="地址" prop="address">
            <Input placeholder="请输入地址" clearable maxlength="150" v-model="addNodeFormData.address"></Input>
          </FormItem>
        </Form>
      </div>
      <Spin size="large" fix v-if="spinLoading"></Spin>
    </cus-modal>

  </div>
</template>
<script>
import {
  getTreeList,
  getSubUnit,
  addUnit,
  getLevelTree,
  editUnit,
  deleteUnit,
  resetPassword,
} from "@/api/organ/organization";
import reportedConfigModal from './components/reportedConfigModal'
import editContextModal from "./components/editContextMenu"
import { getAreaList } from '@/api/organ/dropDown'
export default {
  components: {
    reportedConfigModal,
    editContextModal,
  },
  data() {
    return {
      menuFormData: {},
      organizationOption: [],
      loading: true,
      tableHeight: 0,
      areaList: this.$store.state.selectList.areaList, //区域列表
      spinLoading: false,
      organCol: [
        {
          title: "序号",
          type: "index",
          align: "center",
          minWidth: 70,
        },
        {
          title: "单位名称",
          key: "unitName",
          minWidth: 135,
          align: "center",
        },
        {
          title: "单位代码",
          key: "unitCode",
          minWidth: 145,
          align: "center",
        },
        {
          title: "管理员账号",
          key: "adminUserLoginName",
          minWidth: 135,
          align: "center",
        },
        {
          title: "联系人",
          key: "contactName",
          minWidth: 135,
          align: "center",
        },
        {
          title: "区域",
          key: "kitchenAreaName",
          minWidth: 135,
          align: 'center'
        },
        {
          title: "地址",
          key: "address",
          minWidth: 145,
          align: "center",
        },
        {
          title: "创建时间",
          type: "date",
          key: "gmtCreate",
          minWidth: 165,
          format: "yy-mm-dd",
          align: "center",
        },
        {
          title: "操作",
          slot: "operation",
          minWidth: 205,
          align: "center",
        },
      ],
      orgDataList: [],
      selectedTreeNode: {
        unitName: "",
        children: [],
        id: null,
        unitLevelCode: "",
        unitLevelName: "",
        expand: false,
      }, //用户选择的树节点数据，为用户接下来可能的添加操作提供数据
      addNodeFormData: {
        unitLevelCode: "",
        unitName: "",
        loginName: "",
        kitchenArea: null, //区域编号
        contactName: "",
        contactPhone: "",
        address: "",
        designation: "",
        codeName: "",
        strength: 1,
      },
      ruleValidate: {
        unitLevelCode: [
          { required: true, message: "单位属性必填!", trigger: "change" },
        ],
        
        kitchenArea: [
          { required: true, message: '地区必填', trigger: 'change' }
        ],
        loginName: [
          { required: true, message: "管理员账号必填!", trigger: "blur" },
        ],
        contactName:[
          {required: false},
        ],
        contactPhone: [
          { required: true, message: "联系电话必填!", trigger: "blur" },
        ],
      },
      addOrgModalFlag: false,
      deleteModalTitle: "删除",
      deleteModalFlag: false,
      resetModalTitle: "重置",
      resetModalFlag: false,
      editRow: {},
      modalTitle: "添加",
      levelTree: [],
      addType: "addSubUnit",
      subNodeTypeList: [],
      modalType: "add",
      expandList: [],
      pages: {
        page: 1,
        pageSize: 10,
        pageTotal: 0,
      },
    };
  },
  mounted() {
    setTimeout(() => {
      this.tableHeight = window.innerHeight - 212; // 表格自适应高度
    }, 100);
    window.addEventListener("resize", this.tableHeightChange, true);
    this.onInit();
  },
  watch: {
    addType: {
      handler(val) {
        if (val == "addSubUnit") {
          this.ruleValidate.unitName[0].message = "单位名称必填!";
        } else {
          this.ruleValidate.unitName[0].message = "食堂名称必填!";
        }
      },
    },
  },
  methods: {
    async onInit() {
      await this.getLevelTree();
      this.getTreeList();
      console.log(this.$store.getters);
    },
    // 分页改变
    handleSubmit() {
      let params = {};
      params.unitCode = this.selectedTreeNode.unitCode;
      this.getSubUnit(params);
    },
    // 右键弹出菜单
    handleContextMenu(data) {
      console.log('右键菜单',data);
      this.menuFormData = JSON.parse(JSON.stringify(data));
    },
    // 编辑单位名称
    handleMenuEdit() {
      this.$refs.editContextModal.show(this.menuFormData);
    },
    // 配置
    handleMenuConfig(){
      this.$refs['reportedConfigModal'].show(this.menuFormData);
    },
    getTreeList() {
      this.organizationOption = [];
      getTreeList().then((res) => {
        if (res.code == 1) {
          res.data.expand = true;
          res.data.contextmenu = true;
          this.getExpandStatus(res.data);
          this.organizationOption.push(res.data);
          console.log('树行数据', res.data);
          if (this.organizationOption.length > 0) {
            this.organizationOption[0].selected = true
          }
          let params = {};
          console.log('默认选中', this.selectedTreeNode);
          if (this.selectedTreeNode.unitCode) {
            params.unitCode = this.selectedTreeNode.unitCode;
          } else {
            params.unitCode = res.data.unitCode;
            this.selectedTreeNode = res.data;
            console.log('1', this.selectedTreeNode);
            this.subNodeTypeList = [];
            this.judgeSubType(
              this.levelTree,
              this.selectedTreeNode.unitLevelCode
            );
            console.log('2', this.selectedTreeNode);
          }
          console.log('打印', params);
          this.getSubUnit(params);
          console.log('3', this.selectedTreeNode);
        }
      });
    },
    getLevelTree() {
      return new Promise((resolve) => {
        getLevelTree().then((res) => {
          if (res.code == 1) {
            console.log('Level', res.data);
            this.levelTree.push(res.data);
            resolve(true)
          } else {
            resolve(false)
          }
        });
      })

    },
    tableHeightChange() {
      this.tableHeight = 0;
      setTimeout(() => {
        this.tableHeight = window.innerHeight - 212; // 表格自适应高度
        console.log(this.tableHeight);
      }, 100);
    },
    /**
     *
     * @param {*} row 编辑数据
     * @param {*} index 编辑的数据的下标
     */
    editOrg(row, index) {
      this.modalType = "edit";
      console.log(row);
      this.modalTitle = "编辑";
      this.addType = "addSubUnit";
      let {
        unitLevelCode,
        unitName,
        adminUserLoginName,
        contactName,
        address,
        unitCode,
      } = row;
      this.addNodeFormData.unitLevelCode = unitLevelCode;
      this.addNodeFormData.unitName = unitName;
      this.addNodeFormData.contactName = contactName;
      this.addNodeFormData.loginName = adminUserLoginName;
      this.addNodeFormData.address = address;
      this.addNodeFormData.unitCode = unitCode;
      this.$refs.addOrgModal.show = true;
      this.areaList = this.$store.state.selectList.areaList;
    },
    /**
     *
     * @param {*} row 编辑数据
     * @param {*} index 编辑的数据的下标
     */
    resetPassword(row, index) {
      this.$Modal.confirm({
        title: "重置密码",
        content: "<p>你确定重置密码吗?</p>",
        onOk: () => {
          // this.$Message.info("Clicked ok");
          let params = {};
          params.userId = row.adminUserId;
          params.password = "12345";
          this.resetPasswordAction(params);
        },
      });
    },
    /**
     *
     * @param {*} row 编辑数据
     * @param {*} index 编辑的数据的下标
     */
    resetPasswordAction(params) {
      resetPassword(params).then((res) => {
        if (res.code == 1) {
        }
      });
    },
    deleteOrg(row, index) {
      this.$Modal.confirm({
        title: "删除",
        content: "<p>确定删除吗？</p>",
        onOk: () => {
          // this.$Message.info("Clicked ok");
          let params = {};
          params.unitCode = row.unitCode;
          this.deleteUnit(params);
        },
      });
    },
    deleteUnit(params) {
      deleteUnit(params).then((res) => {
        if (res.code == 1) {
          this.$Message.success("删除成功");
          let paramsSub = {};
          paramsSub.unitCode = this.selectedTreeNode.unitCode;
          this.getTreeList();
          this.getSubUnit(paramsSub);
        }
      });
    },
    //后期添加权限也可能放在这里，比如用户只有某些单位的添加下属单位的权限
    selectTreeNode(data) {
      if (data.length > 0) {
        this.loading = true;
        this.selectedTreeNode = data[0];
        let params = {};
        params.unitCode = data[0].unitCode;
        this.getSubUnit(params);
        this.subNodeTypeList = [];
        this.judgeSubType(this.levelTree, this.selectedTreeNode.unitLevelCode);
      }
    },
    // 查询下级单位
    getSubUnit(params) {
      this.loading = true
      params.currentPage = this.pages.page,
        params.pageSize = this.pages.pageSize
      getSubUnit(
        params
      ).then((res) => {
        if (res.code == 1) {
          this.loading = false;
          this.orgDataList = res.data.list;
          this.pages.pageTotal = res.data.total
        }
      });
    },

    addChildNode() {
      this.modalType = "add";
      if (this.selectedTreeNode && this.selectedTreeNode.unitName) {
        if (this.addType == "addSubUnit") {
          this.modalTitle = "添加";
        } else if (this.addType == "addCanteen") {
          this.modalTitle = "添加食堂";
        }
        this.$refs.addOrgModal.show = true;
        this.areaList = this.$store.state.selectList.areaList;
      }
    },
    statusChange(data) {
      if (!data) {
        this.resetForm();
        this.addNodeFormData.strength = 1
      }
    },
    resetForm() {
      this.$refs.addNodeForm.resetFields();
    },
    asyncDelete() { },
    asyncReset() { },
    renderContent(h, { root, node, data }) {
      return h("span", [h("span", [h("span", data.unitName)])]);
    },
    modalSubmit() {
      let addparams = {};
      addparams.address = this.addNodeFormData.address;
      addparams.contactName = this.addNodeFormData.contactName;
      addparams.loginName = this.addNodeFormData.loginName;
      addparams.kitchenArea = this.addNodeFormData.kitchenArea;
      addparams.parentUnitCode = this.selectedTreeNode.unitCode;
      addparams.unitCode = this.addNodeFormData.unitCode;
      addparams.unitLevelCode =
        this.addType == "addSubUnit"
          ? this.addNodeFormData.unitLevelCode
          : "KITCHEN";
      addparams.unitName = this.addNodeFormData.unitName;
      addparams.contactPhone = this.addNodeFormData.contactPhone;
      addparams.codeName = this.addNodeFormData.codeName;
      addparams.designation = this.addNodeFormData.designation;
      addparams.strength = this.addNodeFormData.strength;
      let editParams = {};
      editParams.address = this.addNodeFormData.address;
      editParams.contactName = this.addNodeFormData.contactName;
      editParams.unitCode = this.addNodeFormData.unitCode;
      editParams.unitName = this.addNodeFormData.unitName;
      editParams.codeName = this.addNodeFormData.codeName;
      editParams.designation = this.addNodeFormData.designation;
      this.$refs.addNodeForm.validate((valid) => {
        if (valid) {
          if (this.modalType == "add") {
            this.addUnit(addparams);
          } else {
            this.editUnit(editParams);
          }
        }
      });
    },
    //新增部门
    addUnit(params) {
      this.spinLoading = true;
      addUnit(params).then((res) => {
        this.spinLoading = false;
        if (res.code == 1) {
          this.selectedTreeNode.expand = true;
          this.selectedTreeNode.children.push(res.data);
          this.$Message.success("新增成功");
          this.$refs.addOrgModal.show = false;
          let params = {};
          params.unitCode = this.selectedTreeNode.unitCode;
          this.getTreeList();
          this.getSubUnit(params);
        }
      });
    },
    editUnit(params) {
      this.spinLoading = true;
      editUnit(params).then((res) => {
        this.spinLoading = false;
        if (res.code == 1) {
          this.$Message.success("编辑成功");
          this.$refs.addOrgModal.show = false;
          let paramsSub = {};
          paramsSub.unitCode = this.selectedTreeNode.unitCode;
          this.getTreeList();
          this.getSubUnit(paramsSub);
        }
      });
    },
    // 判断新建下级单位是食堂还是下级单位
    judgeSubType(levelTree, selectLevelCode) {
      levelTree.forEach((item) => {
        if (item.unitLevelCode == selectLevelCode) {
          if (item.children.length > 1) {
            this.addType = "addSubUnit";
            item.children.forEach((item) => {
              this.subNodeTypeList.push(item);
            });
          } else {
            this.addType = "addCanteen";
          }
        } else {
          if (item.children.length > 0) {
            this.judgeSubType(item.children, selectLevelCode);
          }
        }
      });
      console.log(this.subNodeTypeList);
    },
    changeExPand(data) {
      if (data.expand) {
        this.expandList.push(data.unitCode);
      } else {
        this.expandList = this.expandList.filter(
          (item) => item != data.unitCode
        );
      }
    },
    // 缓存折叠状态
    getExpandStatus(data) {
      console.log(this.expandList);
      if (data.children.length > 0) {
        data.children.forEach((item) => {
          if (this.expandList.includes(item.unitCode)) {
            item.expand = true;
          } else {
            item.expand = false;
          }
          if (item.children.length > 0) {
            this.getExpandStatus(item);
          }
        });
      }
    },
  },
  destroyed() {
    window.removeEventListener("resize", this.tableHeightChange, true);
  },
};
</script>
<style lang="scss" scoped>
@import "./index.scss";
</style>
